/*
 * GeoVISTA Center (Penn State, Dept. of Geography)
 * Copyright (c), 2003-2011,  Jin Chen and Alan M. MacEachren, GeoVISTA Center, Penn State University
 * All Rights Researved.
 *
 * This library is developed and distributed for free usage,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * You can redistribute and/or modify it under the terms of the
 * Simplified BSD License
 *
 *
 *
 *
 *
 *
 *
 *
 * @author: jin Chen 
 * @date: Oct 9, 2003$
 * @version: 1.0
 */
package edu.psu.geovista.app.pcp.toolkits.file;

//import edu.psu.geovista.data.geog.AttributeDescriptionFile;
//import edu.psu.geovista.data.geog.CSVFileDataReader;
import edu.psu.geovista.data.geog.DataSetForApps;
import edu.psu.geovista.data.shapefile.ShapeFileDataReader;
import edu.psu.geovista.db.dbase.DBaseFile;
import edu.psu.geovista.io.csv.CSVFileDataReader;
import edu.psu.geovista.io.csv.GeogCSVReader;
import edu.psu.geovista.io.geog.AttributeDescriptionFile;
import edu.psu.geovista.io.geog.ShapeFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class JShapeFileDataReader extends ShapeFileDataReader{
   public void setFileName (File file) {
      //this.fileName = this.removeExtension(fileName);
      this.dataForApps = this.makeDataSetForApps(this.fileName);
      this.fireActionPerformed(COMMAND_DATA_SET_MADE);
       //for (int i = 0; i < dataSet.length; i++) {
       //   System.out.println(dataSet[i]);
        //}
    }
    public void setFile(File file) {

      this.dataForApps = this.makeDataSetForAppsCSV(file);
      this.fireActionPerformed(COMMAND_DATA_SET_MADE);
    }
    /**
     * first read csv file, if not exist read .dbf file
     * @param file
     * @return
     */
  protected DataSetForApps makeDataSetForApps(File file){
      Object[] shpData = null;
      Object[] dbData =null;
      try {
        /*String dbFileName = fileName + ".dbf";
        DBaseFile db = new DBaseFile(dbFileName);
        Object[] dbData = db.getDataSet();*/

        String fname = fileName + ".csv";
        File datafile=new File(fname);
        //String fname = fileName + ".dbf";
        if(datafile.exists() ){
            CSVFileDataReader csvR=new CSVFileDataReader();
            csvR.setFileName(fname);
            dbData=csvR.getDataSet();
        }
        else{
            fname = fileName + ".dbf";
            datafile=new File(fname);
            if(datafile.exists() ){
                DBaseFile db = new DBaseFile(fname);
                dbData = db.getDataSet();
            }
            else{
                throw new FileNotFoundException("unable to find data file:"+fileName);
            }
        }

        shpData = new Object[dbData.length + 2];
        for (int i = 0; i < dbData.length; i++) {
          shpData[i] = dbData[i];
        }

        ShapeFile shp = new ShapeFile(fileName + ".shp");
        shpData[dbData.length] = this.transform(shp);

		AttributeDescriptionFile desc = null;

		desc = new AttributeDescriptionFile(fileName + ".desc");

		shpData[dbData.length + 1] = desc.getAttributeDescriptions();
      } catch (Exception ex) {
        ex.printStackTrace();
      }
      //this.fireActionPerformed(COMMAND_DATA_SET_MADE);
	  this.dataForApps = new DataSetForApps();
	  dataForApps.setDataObject(shpData);
      return dataForApps;
  }
  /**
   * Read csv file and shpfile together.
   * Assume only one .shp exist in the same folder containing the given <file>
   * @param file  not have to be the csv file, but its name(not include path and extension) should be same as that of .csv file
   *
   * @return
   */
  protected  DataSetForApps makeDataSetForAppsCSV(File file){
      File parent=file.getParentFile() ;

      String fullfileName=null ;
      try {
          fullfileName = file.getCanonicalPath();
      } catch (IOException e) {
          e.printStackTrace();  //To change body of catch statement use Options | File Templates.
      }
      String fileName = this.removeExtension(fullfileName);

      //String fileName;
      Object[] shpData = null;
      try {
        //read csv file
        String dbFileName = fileName + ".csv";

        GeogCSVReader csv = new GeogCSVReader();
        FileInputStream inStream = new FileInputStream(dbFileName);
        Object[] dbData = csv.readFile(inStream);
        shpData = new Object[dbData.length + 2];
        for (int i = 0; i < dbData.length; i++) {
          shpData[i] = dbData[i];
        }
        //2. read shp file
        File shpFile=FileUtils.getFileByExtension(parent,".shp");
        if(shpFile!=null){
            String shpFileName=null;
            try {
                shpFileName =shpFile.getCanonicalPath() ;
            } catch (IOException e) {
                e.printStackTrace();  //To change body of catch statement use Options | File Templates.
            }
            ShapeFile shp = new ShapeFile(shpFileName);
            shpData[dbData.length] = this.transform(shp);
        }
		AttributeDescriptionFile desc = new AttributeDescriptionFile(fileName + ".desc");
		shpData[dbData.length + 1] = desc.getAttributeDescriptions();
      } catch (Exception ex) {
        ex.printStackTrace();
      }
      //this.fireActionPerformed(COMMAND_DATA_SET_MADE);
        this.dataForApps = new DataSetForApps();
        dataForApps.setDataObject(shpData);




      return dataForApps;

  }
  /**
   * Note:unable to make the method static, transformPolygons() need a instance variable to keep track pointCount
   * @param fn
   * @return
   */
  public Object[] readShapeFile(String fn) throws IllegalArgumentException, FileNotFoundException{
      if(fn==null||!fn.endsWith(".shp") ){
         throw new IllegalArgumentException(this.getClass().getName() +"readShapeFile() is passed a non-shp file");

         //todo: file not exist
      }
      File shp=new File(fn);
      if(!shp.exists() ){
          throw new FileNotFoundException(fn +" does not exist. ");
      }

      ShapeFile shpFile = null;
      Object[] shpData =null;
      try {
          shpFile = new ShapeFile(fn);
          shpData = this.transform(shpFile); //
      } catch (IOException e) {
          e.printStackTrace();  //To change body of catch statement use Options | File Templates.
      }
      if(shpData!=null)
        return shpData;
      else
        return new Object[0];
  }

}
